/*
* name;
*/

class Session{
    private socket: Laya.Socket;
	private output: Laya.Byte;
	private length:number;
    constructor(){
		
    }

	public connect(ip:string, port:number): void {
		this.socket = new Laya.Socket();
		this.socket.connectByUrl("ws://" + ip +":" + port);

		this.output = this.socket.output;

		this.socket.on(Laya.Event.OPEN, this, this.onSocketOpen);
		this.socket.on(Laya.Event.CLOSE, this, this.onSocketClose);
		this.socket.on(Laya.Event.MESSAGE, this, this.onMessageReveived);
		this.socket.on(Laya.Event.ERROR, this, this.onConnectError);
	}
	public register_connect_event(object:any, func:Function)
	{
		this.socket.on(Laya.Event.OPEN, object, func);
	}

	public register_connect_error_event(object:any, func:Function)
	{
		this.socket.on(Laya.Event.ERROR, object, func);
	}

	public unregister_connect_event(object:any, func:Function)
	{
		this.socket.off(Laya.Event.OPEN, object, func);
	}

	public unregister_connect_error_event(object:any, func:Function)
	{
		this.socket.off(Laya.Event.ERROR, object, func);
	}

	private onSocketOpen(): void {
		console.log("socket opened");
	}
	
	private onConnectError(e: Event): void {
		console.log("socket connect error");
	}

	private onSocketClose(): void {
		console.log("socket closed");
		
	}

	private onMessageReveived(message: any): void {
		var data = JSON.parse(message);
		this.socket.input.clear();
		if(data.cmd != Opcode.PING)
			console.log("recv cmd %d,data %s", data.cmd, message)
		Global.opcode.call_event(data.cmd, data);
	}

	public Send(cmd:number, data?:any)
	{
		if(data == null)
			data = new Object;
		data['cmd'] = cmd;
		var message: string = JSON.stringify(data);
		this.output.writeUTFBytes(message);
		// for (var i: number = 0; i < message.length; ++i) {
		// 	this.output.writeByte(message.charCodeAt(i));
		// }
		if(data.cmd != Opcode.PING)
			console.log("send cmd %d,data %s", data.cmd, message)
		this.socket.flush();
	}
}


